"use strict";

const config = require('config');
const postgresConfig = config['postgres'];
const DbService	= require("moleculer-db");
const SqlAdapter = require("moleculer-db-adapter-sequelize");


module.exports = function(collection) {
	const cacheCleanEventName = `cache.clean.${collection}`;
	// process.env.POSTGRES_URI = "postgres://postgres:postgres@39.100.84.38:5432/hd2db";
	if (process.env.POSTGRES_URI) {
		return {
			mixins: [DbService],
			adapter: new SqlAdapter(process.env.POSTGRES_URI),
			collection
		};
	}else{
		return {
			mixins: [DbService],
			adapter: new SqlAdapter(postgresConfig["db"], postgresConfig["user"], postgresConfig["password"], {
				dialect: 'postgres',
				host: postgresConfig["host"],
				port: postgresConfig["port"],
				timezone: '+08:00',
				pool: {
					max: 5,
					min: 0,
					idle: 10000
				},
				noSync:false,  //true 不将 model 对应的表同步到数据库； false 会判断如果数据库不存在此表，自动创建 model对应的表
				logging: true,
			}),
			settings:{
				maxPageSize:999999999,
				pageSize:30,
			},
			actions:{
				attributes: {
					async handler() {
						return this.attributes();
					}
				},
				tableName: {
					async handler() {
						return this.tableName();
					}
				},
			},
			methods: {
				async entityChanged(type, json, ctx) {
					await this.clearCache();
					const eventName = `${this.name}.entity.${type}`;
					this.broker.emit(eventName, { meta: ctx.meta, entity: json });
				},
				tableName() {
					return this.adapter.model["getTableName"]();
				},
				attributes() {
					return this.adapter.model.rawAttributes;
				}
			},
			collection
		};
	}
};
